package com.huc.netty.protocol;

import com.huc.netty.handler.RpcClientInitializer;
import com.huc.netty.core.RpcProtocol;
import com.huc.netty.core.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author huc
 * @version 1.0
 * @note 客户端
 * @date 2021/9/16 10:20
 */
@Slf4j
public class NettyClient {

    private final Bootstrap bootstrap;
    private final EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    private String ip;
    private int port;

    public NettyClient(String ip, int port) {
        log.info("初始化客户端NettyClient,{},{}", ip, port);
        bootstrap = new Bootstrap();

        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new RpcClientInitializer());

        this.ip = ip;
        this.port = port;
    }

    /**
     * 发送请求
     *
     * @param protocol
     * @throws InterruptedException
     */
    public void sendRequest(RpcProtocol<RpcRequest> protocol) throws InterruptedException {
        final ChannelFuture future = bootstrap.connect(this.ip, this.port).sync();
        future.addListener(listener -> {
            String serviceAddress = ip + ":" + port;
            if (future.isSuccess()) {
                log.info("远程连接服务 {} 成功！！！", serviceAddress);
            } else {
                log.error("远程连接服务 {} 失败！！！ ", serviceAddress);
                future.cause().printStackTrace();
                eventLoopGroup.shutdownGracefully();
            }
        });
        log.info("===开始传输数据===");
        future.channel().writeAndFlush(protocol);
    }
}
